package com.example.nccdeploytool.controller;

//import cn.hutool.json.JSON;
//import cn.hutool.json.JSONUtil;

import com.example.nccdeploytool.HelloApplication;
import com.example.nccdeploytool.component.BubbleToast;
import com.example.nccdeploytool.entity.FileEntity;
import com.example.nccdeploytool.util.CompressUtil;
import com.example.nccdeploytool.util.ConfigLoader;
import com.example.nccdeploytool.util.FileUtil;
import com.fasterxml.jackson.databind.node.ObjectNode;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.text.Text;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.ResourceBundle;

/**
 * @author 15037
 * @description
 * @date 2025-07-02 15:47
 */
public class PackageFilesController implements Initializable {

    @FXML
    private TextField txtZipLocation;
    @FXML
    private TableView tbZip;
    @FXML
    private TableView tbZipThen;

    private String home;
    private String homeOutput;


    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        this.btnRefresh(null);
    }

    public void btnEdit(ActionEvent actionEvent) {


    }

    /**
     * 刷新解压后的文件
     *
     * @param actionEvent
     */
    public void btnRefreshZipThen(ActionEvent actionEvent) throws IOException {
        ObjectNode json = ConfigLoader.loadConfig();
        // String path = JSON.getByPath(json, "app.package-file", "");

        File outputFile = new File(this.homeOutput);
        if (!outputFile.exists()) {
            outputFile.mkdirs();
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        List<FileEntity> allFiles = FileUtil.getAllFileAndDir(this.homeOutput).stream()
                .map(x -> {
                    FileEntity fileEntity = new FileEntity();
                    // 获取文件时间
                    File file = new File(x);
                    long lastModified = file.lastModified();
                    Date date = new Date(lastModified);
                    fileEntity.setFilePath(x);
                    fileEntity.setUpdatedTime(sdf.format(date));

                    return fileEntity;
                })
                .toList();


        TableColumn<FileEntity, String> filePathCol = new TableColumn<>("filePath");
        filePathCol.setCellValueFactory(new PropertyValueFactory<>("filePath"));
        filePathCol.setPrefWidth(200);

        //设置nameCol中的文本可换行
        filePathCol.setCellFactory(tc -> {

            TableCell<FileEntity, String> cell = new TableCell<>();
            Text text = new Text();
            cell.setGraphic(text);
            cell.setPrefHeight(Control.USE_COMPUTED_SIZE);
            text.wrappingWidthProperty().bind(filePathCol.widthProperty());
            text.textProperty().bind(cell.itemProperty());
            return cell;
        });

//        // 自动调整行高
//        tbZipThen.setRowFactory(tv -> {
//            TableRow<FileEntity> row = new TableRow<>();
//            row.heightProperty().addListener((obs, oldHeight, newHeight) -> {
//                if (newHeight.doubleValue() > row.getMinHeight()) {
//                    row.setMinHeight(newHeight.doubleValue());
//                }
//            });
//            return row;
//        });


        TableColumn<FileEntity, String> updatedTimeCol = new TableColumn<>("updatedTime");
        updatedTimeCol.setCellValueFactory(new PropertyValueFactory<>("updatedTime"));


        tbZipThen.getColumns().setAll(filePathCol, updatedTimeCol);


        ObservableList<FileEntity> data = FXCollections.observableArrayList(
                allFiles
        );


        tbZipThen.setItems(data);
    }

    @FXML
    private void btnUncompressClick() throws IOException {
        System.out.println("uncompress");

        this.btnDelOutput(null); // 删除压缩文件夹

        File destFile = new File(this.homeOutput);

        FileEntity o = (FileEntity) tbZip.getSelectionModel().getSelectedItem();
        if (o == null) {
            BubbleToast.show(HelloApplication.getPrimaryStage(), "未选择行");
            return;
        }

        CompressUtil.unzip(o.getFilePath(), new File(o.getFilePath()).getParent() + File.separator + "output");

    }

    /**
     * 删除解压文件夹output
     *
     * @param actionEvent
     */
    public void btnDelOutput(ActionEvent actionEvent) {
        FileUtil.deleteFolder(new File(this.homeOutput));
    }

    public void btnDelZip(ActionEvent actionEvent) {
        FileEntity o = (FileEntity) tbZip.getSelectionModel().getSelectedItem();
        new File(o.getFilePath()).delete();
    }

    /**
     * 刷新压缩包文件列表
     *
     * @param actionEvent
     */
    public void btnRefresh(ActionEvent actionEvent) {

        try {
            ObjectNode json = ConfigLoader.loadConfig();
//            String path = JSON.getByPath(json, "app.package-file", "");
            String path = json.get("app").get("package-file").asText();
            txtZipLocation.setText(path);
            this.home = path;
            this.homeOutput = path + File.separator + "output";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            List<FileEntity> allFiles = FileUtil.getAllFileAndDir(path).stream()
                    .map(x -> {
                        FileEntity fileEntity = new FileEntity();
                        // 获取文件时间
                        File file = new File(x);
                        long lastModified = file.lastModified();
                        Date date = new Date(lastModified);
                        fileEntity.setFilePath(x);
                        fileEntity.setUpdatedTime(sdf.format(date));

                        return fileEntity;
                    })
                    .filter(x -> x.getFilePath().endsWith(".zip"))
                    .toList();


            TableColumn<FileEntity, String> filePathCol = new TableColumn<>("filePath");
            filePathCol.setCellValueFactory(new PropertyValueFactory<>("filePath"));

            TableColumn<FileEntity, String> updatedTimeCol = new TableColumn<>("updatedTime");
            updatedTimeCol.setCellValueFactory(new PropertyValueFactory<>("updatedTime"));


            tbZip.getColumns().setAll(filePathCol, updatedTimeCol);


            ObservableList<FileEntity> data = FXCollections.observableArrayList(
                    allFiles
            );


            tbZip.setItems(data);


        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
